﻿/* Copyright 2011 Michiel Fortuin
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Diagnostics;


namespace sharplog
{
	/// <summary>
	/// Formater for the BSD Syslog (RFC 3164) protocol. Normally used combined with UDP/TCP sender.
	/// </summary>
	public class BSDSyslog:Formater
	{
		/// <summary>
		/// Application name that must be send with the messages
		/// </summary>
		public string AppName { get; set; }
		/// <summary>
		/// The process id that must be send with the messages. if this is not set, null or empty it wil use the PID.
		/// </summary>
		public string ProcID { get; set; }

		public BSDSyslog()
		{
		}

		public BSDSyslog(string appname, string ProcId = null)
		{
			this.AppName = appname;
			this.ProcID = ProcId;
		}

		/// <summary>
		/// constructs a message with a set of parameters
		/// </summary>
		/// <param name="level"></param>
		/// <param name="facility"></param>
		/// <param name="messageID"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		internal override object ConstructMessage(Level level, Facility facility, string messageID, string message = "")
		{
			int prival = ((int)facility) * 8 + ((int)level);
			string timestamp;
			if(DateTime.Now.Day < 10)
			{
				timestamp = DateTime.Now.ToString("MMM  d HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US"));
			}
			else
			{
				timestamp = DateTime.Now.ToString("MMM dd HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US"));	
			}
			
			string hostname = Dns.GetHostEntry(Environment.UserDomainName).HostName;

			string OutputMessage;
			if(string.IsNullOrWhiteSpace(this.AppName))
			{
				OutputMessage = string.Format("<{0}>{1} {2} {3}", prival, timestamp, hostname, message);
			}
			else
			{
				string procId = string.IsNullOrWhiteSpace(this.ProcID) ? Process.GetCurrentProcess().Id.ToString() : this.ProcID;
				OutputMessage = string.Format("<{0}>{1} {2} {3}[{4}]: {5}", prival, timestamp, hostname, this.AppName, procId, message);
			}
			
			return Encoding.ASCII.GetBytes(OutputMessage);
		}
	}
}
